package com.changgou.goods.service.impl;

import com.alibaba.fastjson.JSON;
import com.changgou.goods.dao.BrandMapper;
import com.changgou.goods.dao.CategoryMapper;
import com.changgou.goods.dao.SkuMapper;
import com.changgou.goods.dao.SpuMapper;
import com.changgou.goods.pojo.*;
import com.changgou.goods.service.SpuService;
import entity.IdWorker;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import tk.mybatis.mapper.entity.Example;

import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * @Author seafwg
 * @Date 2021/12/10 2:44 下午
 * @Version 1.0
 * @description xxx
 */
@Service
public class SpuServiceImpl implements SpuService {

    @Autowired
    private IdWorker idWorker;

    @Autowired
    private SpuMapper spuMapper;

    @Autowired
    private SkuMapper skuMapper;

    @Autowired
    private CategoryMapper categoryMapper;

    @Autowired
    private BrandMapper brandMapper;


    /**
     * 根据spuId逻辑删除
     * @param id
     * @return
     */
    @Override
    @Transactional
    public int logicDelete(Long id) {
        Spu spu = spuMapper.selectByPrimaryKey(id);
        // 检查商品是否下架
        if(spu.getIsMarketable().equals("0")) {
            throw new RuntimeException("未下架的商品不能删除");
        }
        // 逻辑删除
        spu.setIsDelete("1");
        spu.setStatus("0");
        int i = spuMapper.updateByPrimaryKeySelective(spu);
        return i;
    }

    /**
     * 批量上架商品:根据spuId集合批量上架商品
     * @param ids
     */
    @Override
    public int putMany(Long[] ids) {
        Spu spu = new Spu();
        spu.setIsMarketable("1"); // 上架
        // 构建条件:1.生成条件对象 2.创建条件构造器 3.添加条件
        Example example = new Example(Spu.class);
        Example.Criteria criteria = example.createCriteria();
        // 添加ids
        criteria.andIn("id", Arrays.asList(ids));
        // 设置下架
        criteria.andEqualTo("isMarketable", "0");
        // 审核通过
        criteria.andEqualTo("status", "1");
        // 非删除
        criteria.andEqualTo("isDelete", "0");
        int i = spuMapper.updateByExampleSelective(spu, example);
        return i;
    }

    /**
     * 商品的上架
     * @param spuId
     */
    @Override
    public void put(Long spuId) {
        // 查询spu，删除的不能上架，审核未通过的不能上架
        Spu spu = spuMapper.selectByPrimaryKey(spuId);
        if(spu.getIsDelete().equalsIgnoreCase("1")) {
            throw new RuntimeException("删除商品不能上架");
        }
        if(spu.getStatus().equalsIgnoreCase("1")) {
            throw new RuntimeException("审核未通过商品不能上架");
        }
        spu.setIsMarketable("1");
        spuMapper.updateByPrimaryKeySelective(spu);
    }

    /**
     * 商品下架
     * @param spuId
     */
    @Override
    public void pull(Long spuId) {
        // 查询spu,判断是否删除，修改下架状态，更新数据库
        Spu spu = spuMapper.selectByPrimaryKey(spuId);
        if(spu.getIsDelete().equalsIgnoreCase("1")) {
            throw new RuntimeException("该商品已删除，删除的商品无法下架");
        }
        spu.setIsMarketable("0");
        spuMapper.updateByPrimaryKeySelective(spu);
    }

    /**
     * 商品审核
     * @param spuId
     */
    @Override
    public void audit(Long spuId) {
        // 查询商品，判断商品是否删除，实现上架审核
        Spu spu = spuMapper.selectByPrimaryKey(spuId);
        if(spu.getIsDelete().equalsIgnoreCase("1")) {
            throw new RuntimeException("该商品已删除");
        }
        spu.setStatus("1");
        spu.setIsMarketable("1");
        spuMapper.updateByPrimaryKeySelective(spu);
    }

    /**
     * 保存商品：
     * @param goods
     */
    @Override
    public void saveGoods(Goods goods) {
        // 获取spu,增加
        Spu spu = goods.getSpu();
        //通过idWorker设置id
        spu.setId(idWorker.nextId());
        spuMapper.insertSelective(spu);

        // 处理sku
        List<Sku> skuList = goods.getSkuList();
        for (Sku sku : skuList) {
            sku.setId(idWorker.nextId());
            // "spec": "{\"颜色\":\"红色\",\"网络\":\"移动3G\"}",
            String spec = sku.getSpec();
            Map<String, String> map = JSON.parseObject(spec, Map.class);
            String title = spu.getName();
            for (String key : map.keySet()) {
                title += "" + map.get(key);
            }
            sku.setName(title);
            // spuId
            sku.setSpuId(spu.getId());
            // create_time
            sku.setCreateTime(new Date());
            // update_time
            sku.setUpdateTime(sku.getCreateTime());
            // category_id 3级分类 => spu对象中
            Integer category3Id = spu.getCategory3Id();
            sku.setCategoryId(category3Id);
            // category_name 从category表中获取name
            Category category = categoryMapper.selectByPrimaryKey(category3Id);
            sku.setCategoryName(category.getName());
            // brand_name => 从brand表中获取
            Brand brand = brandMapper.selectByPrimaryKey(spu.getBrandId());
            sku.setBrandName(brand.getName());
        }

    }

    /**
     * 根据ID查询spu
     * @param spuId
     * @return
     */
    @Override
    public Goods findById(Long spuId) {
        // query spu
        Spu spu = spuMapper.selectByPrimaryKey(spuId);
        // query sku
        Sku sku = new Sku();
        sku.setSpuId(spuId);
        List<Sku> skuList = skuMapper.select(sku);
        // 封装Goods
        Goods goods = new Goods();
        goods.setSpu(spu);
        goods.setSkuList(skuList);
        return goods;
    }

    /**
     * 修改商品
     * @param goods
     */
    @Override
    public void update(Goods goods) {
        // 商品的更新，直接更新spu,根据spu的ID查询出sku，之后删除sku,再次保存sku
        // 更新spu
        Spu spu = goods.getSpu();
        spuMapper.updateByPrimaryKeySelective(spu);
        // 更新sku
        // 更新sku前先删除库中的sku数据，再次新增
        Sku delSku = new Sku();
        delSku.setSpuId(spu.getId());
        skuMapper.delete(delSku);

        List<Sku> skuList = goods.getSkuList();
        for (Sku sku : skuList) {
            sku.setId(idWorker.nextId());
            // "spec": "{\"颜色\":\"红色\",\"网络\":\"移动3G\"}",
            String spec = sku.getSpec();
            Map<String, String> map = JSON.parseObject(spec, Map.class);
            String title = spu.getName();
            for (String key : map.keySet()) {
                title += "" + map.get(key);
            }
            sku.setName(title);
            // spuId
            sku.setSpuId(spu.getId());
            // create_time
            sku.setCreateTime(new Date());
            // update_time
            sku.setUpdateTime(sku.getCreateTime());
            // category_id 3级分类 => spu对象中
            Integer category3Id = spu.getCategory3Id();
            sku.setCategoryId(category3Id);
            // category_name 从category表中获取name
            Category category = categoryMapper.selectByPrimaryKey(category3Id);
            sku.setCategoryName(category.getName());
            // brand_name => 从brand表中获取
            Brand brand = brandMapper.selectByPrimaryKey(spu.getBrandId());
            sku.setBrandName(brand.getName());
        }
    }
}
